package com.huang.Service.ServiceImpl;

import com.huang.Dao.TxLogDao;
import com.huang.Pojo.Order;
import com.huang.Pojo.TxLog;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class OrderServiceImpl4Listener implements RocketMQLocalTransactionListener {

    @Resource
    private TxLogDao txLogDao;

    @Resource
    private OrderServiceImpl4 orderServiceImpl4;

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object arg) {

        String txId = (String) message.getHeaders().get("txId");

        try {
            Order order=(Order)arg;
            orderServiceImpl4.createOrder(txId,order);
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            return RocketMQLocalTransactionState.ROLLBACK;
        }

    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        String txId = (String) message.getHeaders().get("txId");
        TxLog txLog = txLogDao.findById(txId).get();
        if(txLog != null){
            return RocketMQLocalTransactionState.COMMIT;
        }else {
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }
}
